package com.yh.csx.crm.task;

import com.yh.csx.crm.core.enums.CustPri2PubEnum;
import com.yh.csx.crm.dao.CustomerMapper;
import com.yh.csx.crm.dao.CustomerVisitRecordMapper;
import com.yh.csx.crm.dao.ReportAccountAgeMapper;
import com.yh.csx.crm.dao.ReportOrderStatMapper;
import com.yh.csx.crm.po.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

@Slf4j
@Component
public class PriCust2PubCustTask {

    @Autowired
    CustomerMapper customerMapper;

    @Autowired
    ReportOrderStatMapper reportOrderStatMapper;

    @Autowired
    ReportAccountAgeMapper reportAccountAgeMapper;

    @Autowired
    CustomerVisitRecordMapper customerVisitRecordMapper;

    @Scheduled(cron = "0 0 6 * * ? *")
    public void Task(){
        try {
            Thread.sleep((int)(1800 * Math.random())); // 6点到6点半随机
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("\n******************************************私海转公海开始执行批量***********************************************");
        try {
            this.bizTask();
        }catch (Exception e){
            log.error("私海客户转公海客户跑批异常：" + e.getMessage(), e);
        }
        log.info("\n******************************************私海跑公海结束执行批量***********************************************");

    }

    /**
     * 定时业务：
     *  1.无论新客户还是捡回只要是超过 365 天未下单 从私海强转公海，防止业务人员私自占用客户很长时间
     *  2.只要是业务人员 连续45天未拜访客户，客户一直未下单 ，无应收账款 从私海强转公海
     */
    public void bizTask(){
        // 无论新客户还是捡回只要是超过 365 天未下单 从私海强转公海，防止业务人员私自占用客户很长时间
        ReportOrderStatExample example = new ReportOrderStatExample();
        ReportOrderStatExample.Criteria criteria= example.createCriteria();
        criteria.andNoOrderDaysGreaterThanOrEqualTo(Integer.parseInt(CustPri2PubEnum.LASTORDER_CYCLE.getCode()));
        // criteria.andLastOrderTimeIsNull(); // 为空代表新建至今未下单客户
        List<ReportOrderStat> reportOrderStats = reportOrderStatMapper.selectByExample(example);
        reportOrderStats.forEach(reportOrderStat -> {
            if (!isOrNotAcAll(reportOrderStat.getCustomerNumber())) {
                Customer customer = new Customer();
                customer.setId(reportOrderStat.getCustomerId());
                customer.setSalesUserId(0L);
                customerMapper.updateByPrimaryKeySelective(customer);
            }
        });

        //  只要是业务人员 连续45天未拜访客户，客户一直未下单 ，无应收账款 从私海强转公海
        List<Customer> allCustomers = customerMapper.selectAll();
        allCustomers.forEach(customer -> {
            if (!isOrNotAcAll(customer.getCustomerNumber())) { // 是否有应收账款
                // 规定的天数,没有拜访则抛到公海
                if(!isOrNotCustomerByVisited(customer,Integer.parseInt(CustPri2PubEnum.LASTVISIT_CYCLE.getCode()))){
                    customer.setSalesUserId(0L); //设置0 为公海客户
                    customerMapper.updateByPrimaryKeySelective(customer);
                }
            };
        });
    }

    /**
     * @DESC  查询是否有应收账款
     * @param customerNumber
     * @return
     */
    public boolean isOrNotAcAll(String customerNumber){

        ReportAccountAgeExample reportAccountAgeExample = new ReportAccountAgeExample();
        reportAccountAgeExample.createCriteria().andCustIdEqualTo(customerNumber);
        List<ReportAccountAge> reportAccountAges = reportAccountAgeMapper.selectByExample(reportAccountAgeExample);
        boolean isOrNotAcAll = false; // 默认 没有应收账款
        for (ReportAccountAge reportAccountAge : reportAccountAges) {
            // 如果有应收账款 将标志位设置为ture
            if (reportAccountAge.getAcAll() != null && reportAccountAge.getAcAll().compareTo(BigDecimal.ZERO) == 1 ){
                isOrNotAcAll = true ;
                break;
            }
        }
        if (reportAccountAges.size() == 0){ // 账龄表没有结果集，也设置为ture，防止错误数据造成异常。
            isOrNotAcAll = true ;
        }
        return isOrNotAcAll;
    }

    /**
     * @desc  多少天内是否拜访过
     * @param customer
     * @param days
     * @return
     */
    public boolean isOrNotCustomerByVisited(@NotNull Customer customer , int days){
        boolean isOrNotVisited = true; // 默认拜访
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE,-45);
        CustomerVisitRecordExample example = new CustomerVisitRecordExample();
        CustomerVisitRecordExample.Criteria criteria = example.createCriteria();
        criteria.andCustomerIdEqualTo(customer.getId());
        criteria.andVisitPersonIdEqualTo(customer.getSalesUserId());
        List<CustomerVisitRecord> customerVisitRecords = customerVisitRecordMapper.selectByExample(example);
        if (customerVisitRecords != null && customerVisitRecords.size() > 0){
            CustomerVisitRecord customerVisitRecord = customerVisitRecords.get(customerVisitRecords.size()-1);
            if (customerVisitRecord != null){
                Date lastVisited = customerVisitRecord.getVisitTime();
                if(lastVisited != null && calendar.getTime().getTime() > lastVisited.getTime()){
                    isOrNotVisited = false;
                }
            }
        }else { // 一直没有拜访 比较 新建或者捡回客户的时间?
//            if (customer.getUpdateTime().getTime() < calendar.getTime().getTime()){
//                isOrNotVisited = false;
//            }
        }
        return isOrNotVisited;
    }


    public static void main(String[] args) {
//        new PriCust2PubCustTask().isOrNotCustomerByVisited(new Customer(),5);
    }
}
